package com.ming.util;

import com.ming.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 安全工具类
 * 用于获取当前认证用户信息
 *
 * @author ming
 * @version 1.0
 */
public class SecurityUtils {

    private static JwtUtils jwtUtils;

    /**
     * 设置JwtUtils（用于静态注入）
     */
    public static void setJwtUtils(JwtUtils jwtUtils) {
        SecurityUtils.jwtUtils = jwtUtils;
    }

    /**
     * 获取当前用户ID
     */
    public static Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        // 从authentication中获取用户ID
        Object details = authentication.getDetails();
        if (details instanceof Integer) {
            return (Integer) details;
        }

        return null;
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        return authentication.getName();
    }

    /**
     * 判断当前用户是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated();
    }

    /**
     * 获取当前认证对象
     */
    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}